<script setup lang="ts">
import MyCard from "../../../components/MyCard.vue";
import {Exam, Question, User} from "../../../types/mytypes";
import {nextTick, onMounted, provide, reactive, ref, Ref} from "vue";
import {PageStore, UserStore} from "../../../store/store";
import ExamEditForm from "../../../components/Exam/ExamEditForm.vue";
import AddQuestion from "./AddQuestion.vue";
import {ExamRequest, QuestionRequest} from "../../../request/MyRequset";
import QuestionEditForm from "../../../components/Question/QuestionUpdateForm.vue";
import RandomQuestionForm from "../../../components/Exam/RandomQuestionForm.vue";
import QuestionShow from "../../../components/Question/QuestionShow.vue";
import BindQuestionToExamForm from "../../../components/Exam/BindQuestionToExamForm.vue";
import router from "../../../router/router";

let exam = ref<Exam>({} as Exam)
let show: Ref<boolean> = ref(false);
let enableEdit: Ref<boolean> = ref(false);
let showAddQuestion = ref(false);
let user = ref<User>({} as User)
let userId = ref<number>(-1)
let examId = ref<number>(-1)
let errorMsg = ref("")
let showError = ref(false)
let questionList = ref<Question[]>([])
let showUpdateExamSuc = ref(false)
let showSucNotice = ref(false)
let showRandomQuestion = ref(false)
let showUseQuestionWarn = ref(false)
let randomQuestion = ref<Question[]>([])
let showDelDialog = ref(false)
let delQuestion = ref<Question>()

provide('userId', userId)
provide('examId', examId)

onMounted(async () => {
  await initData();
  userId.value = user.value.id
  examId.value = exam.value.id
  show.value = true;
})
const updateExam = async () => {
  let newExamRes = await ExamRequest.getById(examId.value);
  if (newExamRes.suc) {
    PageStore.setNowExam(newExamRes.data)
    exam.value = newExamRes.data
    showUpdateExamSuc.value = true
    enableEdit.value = false
  } else {
    errorMsg.value = newExamRes.message;
    showError.value = true;
  }
}
const initData = async () => {
  user.value = UserStore.getUser();
  exam.value = PageStore.getNowExam() as Exam;
  let questionRes = await QuestionRequest.getByExamId(exam.value.id as number);
  questionList.value = questionRes.data;
  //console.log(questionRes)
}
const refreshPageInitData = async () => {
  exam.value = (await ExamRequest.getById(examId.value as number)).data;
  let questionRes = await QuestionRequest.getByExamId(exam.value.id);
  questionList.value = questionRes.data;
}
const useQuestionDialog =  (questionList:Question[])=>{
  randomQuestion.value = questionList
  showUseQuestionWarn.value = true
}
const useQuestionToExam = async (q:Question)=>{
  let bindRes = await QuestionRequest.bindExam(exam.value.id,[q])
  if(bindRes.suc){
    showSucNotice.value = true
    showAddQuestion.value = false
    await refreshPageInitData();
  }else{
    showErrorFn(bindRes.message)
  }
}
const useQuestion = async ()=>{
  let clearRes = await QuestionRequest.clearExamQuestion(exam.value.id)
  if(clearRes.suc){
    let bindRes = await QuestionRequest.bindExam(exam.value.id,randomQuestion.value)
    if(bindRes.suc){
      showSucNotice.value = true
      showRandomQuestion.value = false
      showUseQuestionWarn.value = false
      await refreshPageInitData()
    }else{
      showErrorFn(bindRes.message)
    }
  }else{
    showErrorFn(clearRes.message)
  }
}
const updateQuestion = async () => {
  let questionRes = await QuestionRequest.getByExamId(exam.value.id);
  questionList.value = questionRes.data;
  showSucNotice.value = true
}
const showErrorFn= (err:string)=>{
  errorMsg.value = err
  showError.value = true
}
const openAddQuestionPop = () => {
  showAddQuestion.value = true;
}
const showDelQuestionDialog = (index:number)=>{
  delQuestion.value = questionList.value[index]
  showDelDialog.value = true
}

const delQuestionFn = async ()=>{
  let delRes = await QuestionRequest.unbindExam(exam.value.id,[delQuestion.value as Question])
  if(delRes.suc){
    showSucNotice.value=true
    showDelDialog.value = false
    await refreshPageInitData();
  }else {
    showErrorFn(delRes.message)
  }
}

</script>

<template>
  <MyCard  :title="exam.name" back class="exam_manage_container" no_scrollbar>
    <el-skeleton animated v-if="!show"></el-skeleton>
    <div v-else>
      <div class="exam_info_container">
        <ExamEditForm @update="updateExam" :exam="exam" :disable-edit="!enableEdit" btn-text="更新" center
                      disable-select-class></ExamEditForm>
        <div class="edit_switch">
          <el-switch  active-text="编辑" v-model="enableEdit"></el-switch>
        </div>
      </div>
      <div class="question_container">
        <div class="btn_group">
          <el-button type="primary" style="width: 6em;margin-top: 10px" link @click="openAddQuestionPop">添加题目
          </el-button>
          <el-button type="primary" style="width: 6em;margin-top: 10px" link @click="showRandomQuestion=true">自动抽题（推荐）
          </el-button>
          <el-button type="primary" style="width: 6em;margin-top: 10px" link @click="router.push({name:'question'})">前往题库
          </el-button>
        </div>
        <div class="scroll">
          <div class="question_list" style="position: relative" >
            <el-popover trigger="click" v-for="(item,index) in questionList">
              <template #default>
                <div style="display: flex;flex-direction: row;justify-content: center">
                  <el-button @click="showDelQuestionDialog(index)" type="danger" link>删除</el-button>
                </div>
              </template>
              <template #reference>
                <div style="margin: 4px" >
                  <QuestionShow :question="item"></QuestionShow>
                </div>
              </template>
            </el-popover>
          </div>
        </div>
      </div>
    </div>
  </MyCard>

  <el-dialog title="添加题目" v-model="showAddQuestion">
    <BindQuestionToExamForm @use="useQuestionToExam" @err="showErrorFn"></BindQuestionToExamForm>
  </el-dialog>
  <el-dialog title="随机题目" v-model="showRandomQuestion" style="max-height: 30em">
    <RandomQuestionForm @use="useQuestionDialog" @err="showErrorFn" @cancel="showRandomQuestion = false"></RandomQuestionForm>
  </el-dialog>
  <el-dialog width="25em" style="height: auto;min-height: 15em" title="错误" v-model="showError">
    {{ errorMsg }}
  </el-dialog>
  <el-dialog v-model="showUpdateExamSuc" title="更新考试">
    更新考试成功！
  </el-dialog>
  <el-dialog v-model="showSucNotice" title="提示">
    操作成功！
  </el-dialog>
  <el-dialog v-model="showUseQuestionWarn" title="警告">
    这个操作将会清空目前所有的题目，继续吗？
    <el-button @click="useQuestion" type="warning">继续</el-button>
    <el-button @click="showUseQuestionWarn =false">取消</el-button>
  </el-dialog>

  <el-dialog v-model="showDelDialog" title="提示">
    确定要从该考试中删除这道题吗？
    <el-button @click="delQuestionFn" type="warning">确定</el-button>
    <el-button @click="showDelDialog =false">取消</el-button>
  </el-dialog>
</template>

<style scoped lang="scss">
.exam_manage_container {
  height: 100%;


  .exam_info_container {
    border-bottom: 1px #ccc solid;
    position: relative;
  }

  .question_container {
    display: flex;
    flex-direction: column;

    width: 100%;
    .question_list{
      display: flex;
      flex-direction: row;
      flex-wrap: wrap;
      box-sizing: border-box;
      width: 100%;
      padding-bottom: 6em;
    }
    .scroll{
      overflow: auto;
      height: 70vh;
      box-sizing: border-box;
    }
    .btn_group{
      display: flex;
      flex-direction: row;
    }
  }

  .edit_switch {
    position: absolute;
    top: 10px;
    right: 10px;
  }
}
</style>